//
//  WBNetworkManager+Extension.swift
//  新浪微博
//
//  Created by 郭鹏飞 on 2016/11/22.
//  Copyright © 2016年 郭鹏飞. All rights reserved.
//

import Foundation

//MARK: - 封装新浪微博的网络请求方法
extension WBNetworkManager{
    
    //completion 完成回调 [list: 微博字典数组/是否成功]
    //since 最新/下拉  max 旧的/上拉
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0,completion: @escaping (_ list: [[String: AnyObject]]?,_ isSuccess: Bool) -> ()) -> () {
        
        //用 网络工具加载微博 数据
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //Swift 中, Int 可以转换成 AnyObject,但是 Int64不可以
        let params = ["since_id": "\(since_id)",
            "max_id":"\(max_id > 0 ? max_id - 1 : 0)"]
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?, completion: {(json,isSuccess) in
        
            //从 json 中获取 statuses 字典数组
            //如果 as? 失败, result = nil
            let result = json?["statuses"] as? [[String: AnyObject]]
            
            completion(result,isSuccess)
        })
    }
    
    //返回微博的未读数量 - 定时刷新无需提示
    /**
    func unreadCount(completion: (_ count: Int)->()) {
        
        guard let uid = uid else {
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?, completion: { (json, isSuccess) in
            
            let dict = json as?[String : AnyObject]
            let count = dict?["status"] as? Int
            print(count ?? "")
        })
        
        
    }
 */
    var unreadCount: Int{
        
        var count: Int = 0
        
       
        guard let uid = userAccount.uid else {
            return 0
        }
 
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?, completion: { (json, isSuccess) in
            
            let dict = json as?[String : AnyObject]
            count = (dict?["status"] as? Int) ?? 0
            print("检测到新微博\(count)")
        })
        
        return count
    }
    
}

//AMRK: - 用户信息 - 用户登录后,立即执行
extension WBNetworkManager{
    func loadUserInfo(completion: @escaping (_ dict: [String : AnyObject])->()) {
        
        guard let _ = userAccount.uid else {
            return
        }
        
        let infonUrl = "https://api.weibo.com/2/users/show.json"
        let params = ["uid": userAccount.uid]
        
        //发起网络请求
        tokenRequest(URLString: infonUrl, parameters: params as [String : AnyObject]?){ (json,isSuccess) in
            //print(json ?? "")
            
            //完成回调
            completion(json as? [String : AnyObject] ?? [:])
        }
        
    }
}

//MARK: - OAuth 相关方法
extension WBNetworkManager{
    
    //授权码
    //完成回调是否成功
    func loadAccessToken( _ code: String,completion: @escaping (_ isSuccess: Bool)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id" : WBAPPKey,
                      "client_secret" : WBAPPSecret,
                      "grant_type":"authorization_code",
                      "code" : code,
                      "redirect_uri" : WBRedirectURL]
        request(method: .POST, URLString: urlString, parameters: params as [String : AnyObject]?, completion: { (json, isSuccess) in
            
            //失败对用户账户不影响
            
            //print(json ?? "")
            //直接使用字典设置 userAccount 的属性
            self.userAccount.yy_modelSet(with: json as? [String : AnyObject] ?? [:])
            
            //print(self.userAccount)
            
            //加载当前用户信息
            self.loadUserInfo(completion: { (dict) in
                print(dict)
                
                //使用用户信息字典 设置用户信息(头像,昵称)
                self.userAccount.yy_modelSet(with: dict)
                
                //保存模型
                self.userAccount.savaAccount()
                
                // 用户信息加载完成,再回调
                completion(isSuccess)
            })
            
            
        })
        
    }
}
